﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Event;
using System.Messaging;

namespace Framework.Bus
{
    public abstract class EventBus : IEventBus
    {
        #region Private Fields
        protected volatile bool committed = true;
        protected readonly IMessageDispatcher dispatcher;
        protected readonly Queue<EventMetaData> messageQueue = new Queue<EventMetaData>();

        protected readonly object queueLock = new object();

        #endregion

        #region Ctor
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dispatcher"></param>
        /// 
        public EventBus(IMessageDispatcher dispatcher)
        {
            this.dispatcher = dispatcher;
        }

        #endregion


        #region IBus<IEvent> Members

        public void Send(IEvent message, Action<dynamic> beforeCommitAction = null)
        {
            if (beforeCommitAction != null)
            {
                beforeCommitAction(message);
            }
            dispatcher.DispatchMessage(message);
        }

        public void Send(IEnumerable<IEvent> messages)
        {
            foreach (var message in messages)
            {
                dispatcher.DispatchMessage(message);

            }
        }

        public void Post(IEvent message, Action<dynamic> beforeCommitAction = null)
        {
            lock (queueLock)
            {
                messageQueue.Enqueue(new EventMetaData(message, beforeCommitAction));
                committed = false;
            }
        }


        public void Post(IEnumerable<IEvent> messages)
        {
            lock (queueLock)
            {
                foreach (var message in messages)
                {
                    messageQueue.Enqueue(new EventMetaData(message));
                }
                committed = false;
            }
        }
        #endregion

        public abstract void Commit();

        #region IDisposable Members

        public void Dispose()
        {
            if (!this.committed)
            {
                try
                {
                    this.Commit();
                }
                catch
                {
                    throw;
                }
            }
        }

        #endregion
    }
}
